package com.game.logic.fighting.attrs;

import com.coment.game.fight.AttributeManagerLogic;
import com.coment.game.fight.Attrs;
import com.coment.po.AttrsGlobal;
import com.game.dao.attrs.AttrsGlobalDao;
import com.xs.action.exection.ActionException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;

/// 属性管理
@Slf4j
@Service
@AllArgsConstructor
public class AttrsManagement {
    private final ConcurrentHashMap<Integer, Attrs> GlobalAttrs = new ConcurrentHashMap<>();
    private final AttrsGlobalDao dao;

    {
        AttributeManagerLogic.obtainAttrsGHandler = this::get;
    }

    public Attrs get(Integer key) {
        Attrs attrs = GlobalAttrs.get(key);
        if (attrs == null) {
            log.debug("加载 AttrsManagement 缓存 {}", key);
            attrs = new Attrs();
            for (AttrsGlobal attrsGlobal : dao.searchAllByUserInfoId(key)) {
                attrs.update(attrsGlobal.value);
            }
            GlobalAttrs.put(key, attrs);
        }
        return attrs;
    }

    /// 添加全局属性
    public Attrs logAttrsGlobal(Integer userInfoId, Attrs attrs, Object...tag) {
        AttrsGlobal value = new AttrsGlobal(userInfoId, attrs, tag);
        GlobalAttrs.remove(userInfoId);
        this.dao.save(value);
        return this.get(userInfoId);
    }


    /// 清空某项全局属性
    public void clearAttrsGlobal(Integer userInfoId, Object...tag) {
        this.dao.deleteById(AttrsGlobal.obtainGroupHash(userInfoId, tag));
        GlobalAttrs.remove(userInfoId);
    }

    public Attrs search(Integer userInfoId, Object... tag) {
        return this.dao.findById(AttrsGlobal.obtainGroupHash(userInfoId, tag)).orElseThrow(()-> new ActionException("未找到属性")).getValue();
    }
}
